<template>
  <div class="content">
    <div class="search">
      <van-search
        v-model="value"
        placeholder="搜索联系人"
        input-align="center"
        style="padding: 10px 0px;"
      />
    </div>
    <div class="message">
      <div class="list">
        <van-swipe-cell v-for="item in chat_friends_data" :key="item.nickName">
          <van-card :desc="item.lastMsg" :title="item.nickName" @click="toChatingView(item.userId)">
            <template #thumb>
              <van-badge :content="item.unReadNum">
                <div class="child">
                  <img :src="item.faceImage" />
                </div>
              </van-badge>
            </template>
          </van-card>

          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" />
          </template>
        </van-swipe-cell>
      </div>
    </div>
  </div>
</template>

<script lang='ts'>
import { findMyChatMsgOfUnReadData } from "@/api/requests/base";
import {
  addChatDataCaches,
  getFriendDataCache,
  HomeChatListItem,
} from "@/utils/app";
import { ChatMessage } from "@/service/WsService";
import { reactive, ref } from "vue";
import router from "@/router";

export default {
  setup(props: any, context: any) {
    const parent = { ...context };
    const chat_friends_data: any = ref([]);
    let chat_unread_message_num = ref(0);
    const getMyUnReadMsgData = () => {
      findMyChatMsgOfUnReadData().then((res) => {
        const data = res.data;
        for (const friendUserId in data) {
          const friendInfo = getFriendDataCache(friendUserId);
          const msgs: any[] = data[friendUserId].msgs;
          addChatDataCaches(msgs);
          const lastMessage: ChatMessage = msgs[msgs.length - 1];
          const unReadNum = data[friendUserId].unReadNum;
          chat_unread_message_num.value += unReadNum;
          const chatItem = {
            userId: friendUserId,
            nickName: friendInfo?.nickName,
            faceImage: friendInfo?.faceImage,
            lastMsg: lastMessage.msg,
            unReadNum: unReadNum,
          };
          console.log(chatItem);

          chat_friends_data.value.push(chatItem);
        }
        parent.emit("change", chat_unread_message_num.value);
      });
    };
    const toChatingView = (userId: number) => {
      router.push("/chating/" + userId);
    };

    getMyUnReadMsgData();
    return {
      chat_friends_data,
      chat_unread_message_num,
      toChatingView,
    };
  },
};
</script>

<style lang="less">
.message {
  .list {
    .van-swipe-cell {
      height: 54px;
      .van-badge__wrapper {
        position: absolute;
        left: 36px;
      }
      .van-button {
        height: 54px;
      }
    }
  }
}
</style>
